
$(document).ready(function(){
	
	$.ajaxSetup ({ cache: false });
	$(".rtemplates_table").find(".desc").each(function(){display_with_linebreaks($(this))});	// desc should be displayed with linebreaks
	$("#rtemplates_table").find(".set_button").bind("click",function(e){ set_rtemplate(e); });

});	

function set_rtemplate(e)
{
	var setButton = $(e.target);
	var targetBlock = setButton.parents(".rtemplate_block").eq(0);
	var targetId = targetBlock.attr("id");
	
	if (targetBlock.hasClass("current") == true){
		return;
	}	
	
	var title = window.location.pathname.split("/")[2];				// third part on splitting /change/:title/rtemplates at '/'
	var postUrl = '/set/'+title+'/rtemplates'
	var postData = new Object();

	postData["authenticity_token"] = $("*[name='authenticity_token']").eq(0).val();;
	postData["ajax"]="true";
	postData["rtemplate_id"] = targetId;
	
	$.post(
			postUrl,
			postData,
			function(response){
				set_rtemplate_callback(e,response);
			}
	);
}

function set_rtemplate_callback(e, response)
{
	var responseObj = JSON.parse(response);
	if (responseObj["retVal"] != "set"){
		alert(responseObj["retVal"]);				// XXX: Change this action to something better
		return;	
	}	
	var prev_set_block = $("#rtemplates_table").find(".current").eq(0);
	var new_set_block = $(e.target).parents(".rtemplate_block").eq(0);
	
	prev_set_block.removeClass("current");
	new_set_block.addClass("current");
}
